import { ChatroomLastMessage } from "@/apis/db";

export function convertMessage(info: ChatroomLastMessage, userMap?, loginUser?) {
  let plaintext = '';
  const user = userMap?.get(info?.modified_by)
  const user_show = info?.created_by === loginUser?.username ? '您' : (user?.name || info?.modified_by)
  switch (info?.type) {
    case "message_send":
      switch (info?.message?.type) {
        case "img":
          plaintext = "[图片]";
          break;
        case "video":
          plaintext = "[视频]";
          break;
        case "file":
          plaintext = "[文件]";
          break;

        default:
          plaintext = info?.message?.body;
          break;
      }
      break;
    case "chatroom_create":
      plaintext = `${user_show} 创建了群组 ${info?.message?.name}`;
      break;
    case "chatroom_delete":
      plaintext = `${user_show} 解散了该群组`;
      break;
    case "chatroom_adduser":
      const inviteNames = info?.message?.users.map((ele) => userMap?.get(ele)?.name)?.join(" ");
      plaintext = `${user_show} 邀请 ${inviteNames} 加入了群组`;
      break;
    case "chatroom_deluser":
      const currentUsername = loginUser?.username;
      const editorUsername = info?.modified_by;
      const beenDeletedUsers = info?.message?.users;
      const moveOutNames = beenDeletedUsers.map((ele) => userMap?.get(ele)?.name)?.join(" ");
      const editorName = userMap?.get(editorUsername)?.name;

      if (beenDeletedUsers?.includes(currentUsername)) {
        // 当前用户不在群聊
        if (editorUsername === currentUsername) {
          plaintext = `您退出了群组`;
        } else {
          plaintext = `您被 ${editorName} 移除了群组`;
        }
      } else {
        if (beenDeletedUsers?.includes(editorUsername)) {
          plaintext = `${editorName} 退出了群组`;
        } else if (editorUsername === currentUsername) {
          plaintext = `您把 ${moveOutNames} 移出了群组`;
        } else {
          plaintext = `${userMap?.get(editorUsername)?.name} 把 ${moveOutNames} 移出了群组`;
        }
      }

      break;
    case "message_cancel":
      plaintext = `${user_show}撤回了一条消息`;
      break;
    case "chatroom_update":
      plaintext = `${user_show}修改了群信息`;
      break;
    default:
      plaintext = '[未知信息]'
      break;
  }
  return plaintext;
}
